package DataSetPackage;

import java.io.BufferedReader;
import java.io.FileReader;

public class CsvReader extends DataSetReader {
	@Override
	public DataSet readFile(String fileName) throws Exception {
		DataSet dataset = new DataSet();

		BufferedReader br = new BufferedReader(new FileReader(fileName));
		String line = br.readLine();
		String [] attNames = line.split(",");
		for(int i=0;i<attNames.length;i++)
		{
			String name = getNameFromString(attNames[i]);
			if(!name.isEmpty())
			{
				dataset.attributes.add(new Attribute(name));
			}
		}
		line = br.readLine();
		while (line != null) {
			
			if(line.isEmpty())
				continue;
			
			String[] valueNames = line.split(",");
			int[] row = new int[valueNames.length];

			for (int i = 0; i < valueNames.length; i++) {
				valueNames[i] = getNameFromString(valueNames[i]);
				if (valueNames[i].equals("?")|| dataset.getAttribute(i)== null)
					row[i] = -1;
				else
				{
					int index = dataset.getAttribute(i).getNominalIndex(valueNames[i]);
					if(index == -1)
					{
						index = dataset.getAttribute(i).getNumberOfNominal();
						dataset.getAttribute(i).nominals.add(valueNames[i]);
					}
					
					row[i] = index;
				}
			}
			dataset.data.add(row);
			line = br.readLine();
		}
		br.close();
		return dataset;
	}
}
